package com.bootdo.wx.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.date.DateUtil;
import com.bootdo.common.config.WxMaConfiguration;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.excel.ExtractExcelUtils;
import com.bootdo.wx.constant.Constants;
import com.bootdo.wx.dao.*;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.MemberExtractService;
import com.bootdo.wx.service.OrderComService;
import com.github.pagehelper.PageInfo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Null;
import java.math.BigDecimal;
import java.util.*;


@Service
public class MemberExtractServiceImpl implements MemberExtractService {
	@Autowired
	private MemberExtractDao memberExtractDao;
	@Autowired
	private CmsContentDao cmsContentDao;
	@Autowired
	private OrderComService orderComService;
	@Autowired
	private MemberPriceDao memberPriceDao;
	@Autowired
	private WxMaProperties properties;
	@Autowired
	private MemberUserDao memberUserDao;

	@Autowired
	private OrderComDao orderComDao;

	@Override
	public MemberExtractDO get(String id){
		return memberExtractDao.get(id);
	}

	@Override
	public List<MemberExtractDO> list(Map<String, Object> map){
		return memberExtractDao.list(map);
	}

	@Override
	public int count(Map<String, Object> map){
		return memberExtractDao.count(map);
	}

	@Override
	public int save(MemberExtractDO memberExtract){
		return memberExtractDao.save(memberExtract);
	}

	@Override
	public int update(MemberExtractDO memberExtract){
		return memberExtractDao.update(memberExtract);
	}

	@Override
	public int remove(String id){
		return memberExtractDao.remove(id);
	}

	@Override
	public int batchRemove(String[] ids){
		return memberExtractDao.batchRemove(ids);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public Map<String, Object> getExtractList(Map<String, Object> map) {
		map.put("delFlag","0");
		Map<String,Object> returnMap = new HashMap<>();
		PageHelperUtils.page(map);
		List<Map<String, Object>> list = orderComDao.extracSettlement(map);
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
		map.put("status","1");
		BigDecimal tPrice = memberExtractDao.getNumByUserT(map);
		returnMap.put("list",pageInfo);
		returnMap.put("tPrice",tPrice);
		return returnMap;
	}



	@Override
	public R goExtract(Map<String, Object> map) {
		if (!StringUtils.isBlank(map.get("orderId").toString())) {
		String userId = map.get("userId").toString();
		OrderComDO orderComDO = orderComDao.getOrderComDO(map);
		BigDecimal allMoney = orderComDO.getComPrice();
		if(allMoney.compareTo(BigDecimal.ZERO)==0){
			return R.error("提现金额不能为0");
		}
		map.clear();
		map.put("type", "extract-Money");
		CmsContentDO cmsContentDo = cmsContentDao.list(map).get(0);
		BigDecimal minMoney = new BigDecimal(cmsContentDo.getValue());   //提现最低金额
		map.clear();
		map.put("userId", userId);
		if (allMoney.compareTo(minMoney) == -1) {
			return R.error("提现金额最小为 " + minMoney);
		}
			MemberExtractDO extractDO = new MemberExtractDO();
			Date date = new Date();
			String extractId = UuidUtil.get32UUID();
			extractDO.setId(extractId);
			extractDO.setDelFlag(0);
			extractDO.setCreateAt(date);
			extractDO.setUpdateAt(date);
			extractDO.setStatus(0);
			extractDO.setUserId(userId);
			extractDO.setType("微信");
			extractDO.setMoney(allMoney);
			memberExtractDao.save(extractDO);
			//填入会员余额表
			MemberPriceDO priceDO = new MemberPriceDO();
			priceDO.setId(UuidUtil.get32UUID());
			priceDO.setGId(extractDO.getId());
			priceDO.setType(1);
			priceDO.setDelFlag(0);
			priceDO.setCreateAt(date);
			priceDO.setUpdateAt(date);
			priceDO.setUserId(userId);
			priceDO.setPrice(allMoney);
			memberPriceDao.save(priceDO);
			//填充订单收益表
			orderComDO.setExtractId(extractId);
			orderComDO.setUpdateAt(date);
			orderComDao.update(orderComDO);
		}else {
			String userId = map.get("userId").toString();
			map.clear();
			map.put("userId", userId);
			Map<String,Object> moneyMap = orderComService.getMemberCom(map);
			BigDecimal allMoney = (BigDecimal)moneyMap.get("canExPrice");//可提现余额
			if(allMoney.compareTo(BigDecimal.ZERO)==0){
				return R.error("提现金额不能为0");
			}
			map.clear();
			map.put("type", "extract-Money");
			CmsContentDO cmsContentDo = cmsContentDao.list(map).get(0);
			BigDecimal minMoney = new BigDecimal(cmsContentDo.getValue());   //提现最低金额
			if (allMoney.compareTo(minMoney) == -1) {
				return R.error("提现金额最小为 " + minMoney);
			}
			map.put("status", "2");
			map.put("delFlag","0");
            List<Map<String, Object>> list = orderComDao.extractList(map);
            if (list.size()>0){
				Date date = new Date();
				for (Map<String, Object> orderCom : list) {
					BigDecimal comPrice = (BigDecimal)orderCom.get("com_price");
					MemberExtractDO extractDO = new MemberExtractDO();
					String extractId = UuidUtil.get32UUID();
					extractDO.setId(extractId);
					extractDO.setDelFlag(0);
					extractDO.setCreateAt(date);
					extractDO.setUpdateAt(date);
					extractDO.setStatus(0);
					extractDO.setUserId(userId);
					extractDO.setType("微信");
					extractDO.setMoney(comPrice);
					memberExtractDao.save(extractDO);
					//填入会员余额表
					MemberPriceDO priceDO = new MemberPriceDO();
					priceDO.setId(UuidUtil.get32UUID());
					priceDO.setGId(extractDO.getId());
					priceDO.setType(1);
					priceDO.setDelFlag(0);
					priceDO.setCreateAt(date);
					priceDO.setUpdateAt(date);
					priceDO.setUserId(userId);
					priceDO.setPrice(comPrice);
					memberPriceDao.save(priceDO);
					//填充订单收益表
					String id = orderCom.get("id").toString();
					OrderComDO orderComDO = orderComDao.get(id);
					orderComDO.setExtractId(extractId);
					orderComDO.setUpdateAt(date);
					orderComDao.update(orderComDO);
				}
			}
		}
		return R.ok();
	}

	@Override
	public List<Map<String,Object>> getList(Map<String, Object> map) {
		return memberExtractDao.getList(map);
	}

	@Override
	public int getListCount(Map<String, Object> map) {
		return memberExtractDao.getListCount(map);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R shen(MemberExtractDO memberExtractDO) {
		String id = memberExtractDO.getId();
		MemberExtractDO extractDO = memberExtractDao.get(id);
		if (extractDO.getStatus() != 0) {
			return R.error("已经提现过了，请刷新页面");
		}
		if(memberExtractDO.getStatus()==-1){
			memberExtractDO.setStatus(1);
		}
		memberExtractDO.setUpdateAt(new Date());
		memberExtractDao.update(memberExtractDO);

		//OrderComDO orderComDO = new OrderComDO();
		//orderComDO.setExtractId(memberExtractDO.getId());
		if (memberExtractDO.getStatus() == 2) {
			//如果拒绝提现，修改我的余额记录
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("gId",memberExtractDO.getId());
			map.put("type", "1");
			MemberPriceDO priceDO = memberPriceDao.list(map).get(0);
			MemberPriceDO memberPriceDO = new MemberPriceDO();
			memberPriceDO.setId(priceDO.getId());
			memberPriceDO.setUpdateAt(new Date());
			memberPriceDO.setDelFlag(1);
			memberPriceDao.update(memberPriceDO);
			//修改返利表
			Map<String,Object> comMap = new HashMap<String,Object>();
			comMap.put("extract_id",memberExtractDO.getId());
			OrderComDO orderComDO = orderComDao.list(comMap).get(0);
			OrderComDO comDO = new OrderComDO();
			comDO.setId(orderComDO.getId());
			comDO.setExtractId("null");
			comDO.setUpdateAt(new Date());
			orderComService.save(comDO);
			//orderComDO.setStatus(2);
			//orderComService.update(orderComDO);


		}/*else if (memberExtractDO.getStatus() == 1){




			*//*Map<String,Object> map = new HashMap<String,Object>();
			map.put("gId",memberExtractDO.getId());
			map.put("type", "1");
			MemberPriceDO priceDO = memberPriceDao.list(map).get(0);
			MemberPriceDO memberPriceDO = new MemberPriceDO();
			memberPriceDO.setId(priceDO.getId());
			memberPriceDO.setUpdateAt(new Date());
			memberPriceDO.setDelFlag(1);
			memberPriceDao.update(memberPriceDO);

			//orderComDO.setStatus(4);
			//orderComService.update(orderComDO);*//*


		}*/
		String result = memberExtractDO.getStatus()==1?"提现成功":"拒绝提现";
		MemberUserDO memberUserDO = memberUserDao.get(extractDO.getUserId());

		try {
			//发送订阅消息
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
			subscribeMessage.setToUser(memberUserDO.getWechatOpenId());
			subscribeMessage.setTemplateId(Constants.mesage.MODE_EXTRACT_STATUS);
			subscribeMessage.setPage(Constants.mesage.address.ADDRESS_INDEX_INDEX);
			List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
			for (int i = 0; i < 4; i++) {
				WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
				switch (i) {
					case 0:
						data.setName("time1");
						data.setValue(DateUtil.format(extractDO.getCreateAt(),DateUtils.DATE_TIME_PATTERN));
						break;
					case 1:
						data.setName("amount3");
						data.setValue(extractDO.getMoney()+"");
						break;
					case 2:
						data.setName("thing2");

						data.setValue("微信零钱");
						break;
					case 3:
						data.setName("phrase4");
						data.setValue(result);
						break;
					// case 4:
					// 	data.setName("thing5");
					// 	data.setValue("");
					// 	break;
					default:
						break;
				}
				list.add(data);


			}
			subscribeMessage.setData(list);
			wxService.getMsgService().sendSubscribeMsg(subscribeMessage);//发送订阅消息

		} catch (WxErrorException e) {
			e.printStackTrace();
		}

		return R.ok();
	}

	/*导出excel。*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void exportExcel(List<Map<String,Object>> userList,
							ServletOutputStream out,HttpServletRequest request) {
		ExtractExcelUtils.exportUserExcel(userList, out);
	}

	@Override
	public BigDecimal getNumByUserT(Map<String, Object> map) {
		return memberExtractDao.getNumByUserT(map);
	}

}
